import React, { Component } from 'react';
import { Modal, message, Form, Table, DatePicker, Input,  Button, Popconfirm } from 'antd';
import { messages } from 'share/common';
import moment from 'moment';
import invoiceManagementService from '../invoice-management.service';
import { connect } from 'react-redux';

const { TextArea } = Input;
const FormItem = Form.Item;

class TimedReminder extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      loading: true,
      confirmLoading: false,
      pagination: {
        total: 0,
        page: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      columns: [
        {
          title: messages('setting.key743'/*提醒时间*/),
          dataIndex: 'time',
          width: '30%',
          render: time => <span>{time}</span>
        },
        {
          title: messages('setting.key744'/*提醒内容*/),
          dataIndex: 'params.content',
          render: (content) => <span>{content}</span>
        },
        {
          title: messages('common.operation')/*操作(*/,
          dataIndex: 'operate',
          width: '10%',
          render: (text, record) => (
            <span>
                <Popconfirm key={record.key} title={messages('common.confirm.delete')/*确定要删除吗？(*/} onConfirm={(e) => this.handleDeleteReminder(e, record)}>
                  <a>{messages('common.delete')/*删除(*/}</a>
                </Popconfirm>
             </span>
          )
        }
      ]
    };
  }

  // 删除数据
  handleDeleteReminder = (e, record) => {
    e.stopPropagation();
    let deleteReminder = () => {
      invoiceManagementService.deleteItem([record.id])
        .then((resp) => {
          if (resp.status === 200) {
            message.success(messages('setting.key213'/*删除成功*/));
            this.getInvoiceScheduleList();
          }
        })
        .catch((error) => {
          message.error(messages('common.operate.filed')/*操作失败(*/);
          this.setState({ loading: false });
        });
    };
    this.setState({ loading: true }, () => {
      deleteReminder();
    });
  };

  handleShowModal = () => {
    this.setState({ modalVisible: true });
  };

  handleHideModal = () => {
    this.setState({ modalVisible: false });
  };

  componentWillMount() {
    this.getInvoiceScheduleList();
  }

  getInvoiceScheduleList() {
    let { pagination, data, loading } = this.state;
    const { companyOID } = this.props.company;
    invoiceManagementService.invoiceSchedule(companyOID, pagination.page, pagination.pageSize)
      .then((resp) => {
        pagination.total = resp.data.total || 0;
        resp.data.rows.map((item, index) => {
          item.key = item.id;
          item.time = `${item.month}${messages('setting.key745'/*月*/)}${item.date}${messages('setting.key746'/*日*/)}${item.hour}${messages('setting.key747'/*时*/)}`;
          item.params = JSON.parse(item.params);
        });
        data = resp.data.rows;
        console.log(data);
      })
      .catch((error) => {
        message.error(messages('common.error'));
      })
      .finally(final => {
        loading = false;
        this.setState({ pagination, data, loading });
      });
  }

  handleOk = () => {
    const { companyOID } = this.props.company;
    this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        this.setState({ confirmLoading: true });
        let time = new Date(fieldsValue['time'].format('YYYY-MM-DD HH:mm:ss'));
        let content = { 'content': fieldsValue['content'] };
        let scheduleParams = {
          code: 'InvoiceScheduledNoticeTask',
          companyOID: companyOID,
          description: 'invoice scheduled notice',
          enabledFlag: true,
          month: time.getMonth() + 1,
          date: time.getDate(),
          hour: time.getHours(),
          params: JSON.stringify(content)
        };
        invoiceManagementService.addSchedule(scheduleParams)
          .then((resp) => {
            if (resp.data.success) {
              this.props.form.resetFields();
              message.success(messages('setting.key211'/*保存成功*/));
              this.setState({ confirmLoading: false, modalVisible: false, loading: true }, () => {
                this.getInvoiceScheduleList();
              });
            }
          })
          .catch(error => {
            this.setState({ confirmLoading: false });
            message.error(messages('common.save.filed'));
          });
      }
    });
  };

  onChange = (_pagination) => {
    let { pagination, loading } = this.state;
    pagination.page = _pagination.current - 1;
    pagination.pageSize = _pagination.pageSize;
    loading = true;
    this.setState({
      pagination,
      loading
    }, () => {
      this.getInvoiceScheduleList();
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, modalVisible, confirmLoading, columns, pagination, data } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 10, offset: 1 }
    };
    const config = {
      rules: [{ type: 'object', required: true, message: 'Please select time!' }],
    };
    const hourFormat = `MM${messages('setting.key745'/*月*/)} DD${messages('setting.key746'/*日*/)} HH${messages('setting.key747'/*时*/)}`;

    return (
      <div>
        <div className="table-header-api">
          <Button type="primary" className="addSchedule" onClick={this.handleShowModal}>
            {messages('setting.key120'/*定时提醒*/)}</Button> {/*定时提醒*/}
          <div
            className="table-header-api-title">{messages('common.total', { total: `${this.state.pagination.total}` })}</div>
          {/*共搜索到*条数据*/}
        </div>

        <Modal title={messages('setting.key120'/*定时提醒*/)}
               visible={modalVisible}
               onOk={this.handleOk}
               confirmLoading={confirmLoading}
               onCancel={this.handleHideModal}>
          <Form>
            <FormItem {...formItemLayout} label={messages('setting.key743'/*提醒时间*/)}>  {/*提醒时间*/}
              {getFieldDecorator('time', { config, initialValue: moment('120109', hourFormat) })(
                <DatePicker showTime format="MM月 DD日 HH时"/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key744'/*提醒内容*/)}>  {/*提醒内容*/}
              {getFieldDecorator('content', {
                rules: [{
                  required: true,
                  message: messages('common.please.enter')
                }],
                initialValue: messages('setting.key765'/*请尽快报销当年发票*/)
              })(
                <TextArea maxLength="200"/>
              )}
            </FormItem>
          </Form>
        </Modal>

        <Table
          rowKey='key'
          loading={loading}
          dataSource={data}
          pagination={pagination}
          columns={columns}
          size="middle"
          onChange={this.onChange}
          bordered/>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company
  };
}

const WrappedInvoiceManagement = Form.create()(TimedReminder);
export default connect(mapStateToProps)(WrappedInvoiceManagement);
